﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLReportExport
{
    class XMLExport
    {
        private static void GenerateXmlReport(string file)
        {
            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month-1, 1);
            DateTime end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 
                DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));
            using (BookstoreDataClassesDataContext context = new BookstoreDataClassesDataContext())
            {
                using (XmlTextWriter writer = new XmlTextWriter(file, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.Indentation = 1;
                    writer.IndentChar = '\t';

                    var sales =
                        from s in context.Sales
                        join b in context.Books on s.BookId equals b.BookId
                        where s.SaleDate > start && s.SaleDate < end
                        select new { isbn = b.ISBN, amount = s.Amount, income = (b.Price * s.Amount) };
                    Dictionary<string, SaleInfo> salesInfo = new Dictionary<string, SaleInfo>();
                    foreach (var item in sales)
                    {
                        if (!salesInfo.ContainsKey(item.isbn))
                        {
                            salesInfo.Add(item.isbn, new SaleInfo(item.amount, item.income));
                        }
                        else
                        {
                            salesInfo[item.isbn].Amount += item.amount;
                            salesInfo[item.isbn].Income += item.income;
                        }
                    }
                    writer.WriteStartDocument();
                    writer.WriteStartElement("sales-report");
                    string startDate = start.Day + "/" + start.Month + "/" + start.Year;
                    writer.WriteAttributeString("start-date", startDate);
                    string endDate = end.Day + "/" + end.Month + "/" + end.Year;
                    writer.WriteAttributeString("end-date", endDate);
                    foreach (var sale in salesInfo)
                    {
                        writer.WriteStartElement("book-sale");
                        writer.WriteElementString("isbn", sale.Key);
                        writer.WriteElementString("amount", sale.Value.Amount.ToString());
                        writer.WriteElementString("income", sale.Value.Income.ToString());
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
            }
        }

        static void Main()
        {
            GenerateXmlReport("report.xml");
        }
    }
}
